<template>
  <div class="knowledge-base">
    <ContentWrap>
      <el-form ref="formRef" :rules="rules" :inline="true" :model="ruleForm" class="demo-form-inline search">
        <el-form-item>
          <el-button @click="handleAdd('add')" :icon="Plus" plain type="primary">添加</el-button>
          <el-button @click="handleImport" :icon="Download" plain type="warning">导入</el-button>
        </el-form-item>
        <el-form-item style="float: right; margin-right: 0">
          <el-button @click="goBack" :icon="ArrowLeft" plain type="info">返回</el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>
    <ContentWrap>
      <div style="height: 560px">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2 :columns="columns" :data="tableModule.tableData" :width="width" :height="height" />
          </template>
        </el-auto-resizer>
      </div>
      <el-pagination :current-page="tableModule.currentPage" :page-size="tableModule.pageSize"
        :page-sizes="[10, 20, 30, 50]" :small="false" :disabled="false" :background="false"
        layout="total, sizes, prev, pager, next, jumper" :total="tableModule.count" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </ContentWrap>
  </div>
  <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="500" fullscreen>
    <el-form ref="ruleFormRef" :rules="rules" :model="formData" label-position="right" label-width="auto">
      <el-form-item label="所属图谱" prop="graphName">
        <el-input v-model="formData.graphName" placeholder="请输入所属图谱" :disabled="true" />
      </el-form-item>
      <el-form-item label="所属图谱ID" prop="graphId">
        <el-input v-model="formData.graphId" placeholder="请输入所属图谱ID" :disabled="true" />
      </el-form-item>
      <el-form-item label="知识库作者" prop="author">
        <el-input v-model="formData.author" placeholder="请输入知识库作者" />
      </el-form-item>
      <el-form-item label="知识库内容" prop="content">
        <el-input v-model="formData.content" placeholder="请输入知识库内容" :autosize="{ minRows: 10, maxRows: 10 }"
          type="textarea" clearable />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="submitForm(ruleFormRef)" type="primary" :auto-insert-space="true">确定</el-button>
        <el-button @click="Cancel(ruleFormRef)" :auto-insert-space="true">取消</el-button>
      </div>
    </template>
  </el-dialog>
  <importForm ref="importFormRef" />
</template>
<script lang="tsx" setup>
import { useRouter, useRoute } from 'vue-router'
const route = useRoute()
const router = useRouter()
import { Plus, Upload, Download, ArrowLeft } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, Column, UploadProps } from 'element-plus'
import * as FormApi from '@/api/knowledge/knowledgeBase/index'
import dayjs from 'dayjs'
import importForm from './importForm.vue'
const formRef = ref<FormInstance>()
const ruleFormRef = ref<FormInstance>()
interface FormData {
  graphName: string
  graphId: string
  author: string
  content: string
}
const goBack = () => {
  router.go(-1)
}
// 添加弹窗表单
const formData = reactive<FormData>({
  graphName: route.query.graphName, // 所属图谱
  graphId: route.query.graphId, // 所属图谱ID
  author: '', // 知识库作者
  content: '', // 知识库内容
  publishTime: dayjs().format('YYYY-MM-DD HH:mm:ss') // 发布时间
})
interface RuleForm {
  graphName: string
  graphId: string
  author: string
  content: string
}
const rules = reactive<FormRules<RuleForm>>({
  graphName: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
  graphId: [{ required: true, message: '请输入节点名称', trigger: 'blur' }],
  author: [{ required: true, message: '请选择所属知识库', trigger: 'change' }],
  content: [{ required: true, message: '请输入节点名称', trigger: 'blur' }]
})
// 图谱类型
const options = [
  {
    label: '图谱知识库',
    value: '1'
  },
  {
    label: '知识库',
    value: '2'
  }
]
const ruleForm = reactive<RuleForm>({
  graphName: '',
  graphId: '',
  region: '',
  name: ''
})
let dialogTitle = ref<string>('')
let dialogFormVisible = ref(false)
const formLabelWidth = '70px'
const form = reactive({
  name: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: ''
})
// 弹窗操作类型
let operationType = ref<String>('')
// 表格数据
const tableModule = reactive({
  tableData: [], // 表格数据
  currentPage: 1, // 表格分页：当前页
  pageSize: 10, // 表格分页：每页显示条目个数
  count: 1 // 表格分页：总记录数
})
// 重置表单
const resetFormFcn = async (formData) => {
  Object.keys(formData).filter((item) => {
    delete formData[item]
  })
}
// 列表查询
const getTableData = async () => {
  // console.log(route.query.id)
  const params = {
    // pageNo: tableModule.currentPage,
    // pageSize: tableModule.pageSize,
    graphName: route.query.graphName, // 所属图谱
    graphId: route.query.graphId // 所属图谱ID
  }
  console.log(route.query.graphId)
  FormApi.getKnowledgePage(route.query.graphId).then((res) => {
    tableModule.tableData = res.list
    tableModule.count = res.total
    dialogFormVisible.value = false
    // ElMessage({
    // message: '查询成功',
    // grouping: true,
    // showClose: true,
    // type: 'success'
    // })
  })
}
getTableData()
// 弹窗取消
const Cancel = (formEl: FormInstance | undefined) => {
  dialogFormVisible.value = false
}
// 弹窗确定
const submitForm = async (formEl: FormInstance | undefined) => {
  console.log(formEl)
  const params = { ...formData }
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(operationType)
      if (operationType.value == 'add') {
        FormApi.insertHybaseKnowledge(params).then((res) => {
          console.log(res)
          dialogFormVisible.value = false
          formEl.resetFields()
          ElMessage({
            message: '添加成功',
            grouping: true,
            showClose: true,
            type: 'success'
          })
          // resetFormFcn(formData)
          getTableData()
        })
      } else if (operationType.value == 'edit') {
        FormApi.updateHybaseKnowledge(params).then((res) => {
          console.log(res)
          dialogFormVisible.value = false
          formEl.resetFields()
          ElMessage({
            message: '修改成功',
            grouping: true,
            showClose: true,
            type: 'success'
          })
          // resetFormFcn(formData)
          getTableData()
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 修改
const edit = (type: string, data: any) => {
  operationType.value = type
  dialogFormVisible.value = true
  dialogTitle.value = '修改关系维护'
  formData.author = data.rowData.author
  formData.content = data.rowData.content
  formData.id = data.rowData.id
}
// 删除
const deleteFcn = (data: any) => {
  ElMessageBox.confirm('确定永久删除该条数据吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      console.log(data.rowData.id)
      FormApi.deleteHybaseKnowledge(data.rowData.id)
        .then((res: any) => {
          ElMessage({
            type: 'success',
            grouping: true,
            showClose: true,
            message: '删除已完成'
          })
          getTableData()
        })
        .catch((error: any) => {
          ElMessage({
            message: error,
            grouping: true,
            showClose: true,
            type: 'error'
          })
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        grouping: true,
        showClose: true,
        message: '删除已取消'
      })
    })
}
// 添加
const handleAdd = (type: string) => {
  operationType.value = type
  dialogFormVisible.value = true
  dialogTitle.value = '添加关系维护'
}
// 导入
const importFormRef = ref()
const handleImport = () => {
  importFormRef.value.open()
}

// 分页：pageSize 改变时会触发
const handleSizeChange = (val: number) => {
  tableModule.pageSize = val
  getTableData()
}

// 分页：currentPage 改变时会触发
const handleCurrentChange = (val: number) => {
  tableModule.currentPage = val
  getTableData()
}
const columns: Column<object>[] = [
  {
    key: 'id',
    title: '知识库ID',
    dataKey: 'id',
    width: 330,
    align: 'center',
    cellRenderer: ({ cellData: id }) => <div>{id}</div>
  },
  {
    key: 'author',
    title: '知识库作者',
    dataKey: 'author',
    width: 230,
    align: 'center',
    cellRenderer: ({ cellData: author }) => <div>{author}</div>
  },
  {
    key: 'content',
    title: '知识库内容',
    dataKey: 'content',
    width: 230,
    align: 'center',
    cellRenderer: ({ cellData: content }) => (
      <el-tooltip content={content}>
        {
          <span
            class="table-content"
            style="
  overflow: hidden;
  height: 18px;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 1;"
          >
            {content}
          </span>
        }
      </el-tooltip>
    )
  },
  {
    key: 'publishTime',
    title: '发表时间',
    dataKey: 'publishTime',
    width: 230,
    align: 'center'
  },
  {
    key: 'createTime',
    title: '创建时间',
    dataKey: 'createTime',
    width: 230,
    align: 'center'
  },
  {
    key: 'operations',
    title: '操作',
    cellRenderer: (data) => (
      <>
        <el-button onClick={edit.bind(this, 'edit', data)} type="success" size="small">
          修改
        </el-button>
        <el-button onClick={deleteFcn.bind(this, data)} type="danger" size="small">
          删除
        </el-button>
      </>
    ),
    width: 350,
    align: 'center'
  }
]
</script>
<style lang="scss" scoped>
.knowledge-base {
  .search {
    .el-form-item {
      margin: 0 32px 0 0;
    }
  }
}

.table-content {}

.font-color-red {
  // #f57070
  color: red;
}

// 弹窗表单组件样式
.demo-form-inline .el-input {
  --el-input-width: 230px !important;
}

.demo-form-inline .el-select {
  --el-select-width: 230px !important;
}
</style>
